package com.crm.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.ListJoin;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.math3.geometry.spherical.twod.Circle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.crm.entity.Department;
import com.crm.entity.Module;
import com.crm.entity.User;
import com.crm.entity.UserChecks;
import com.crm.repository.ModuleRepository;
import com.crm.repository.UserCheckRepository;
import com.crm.repository.UserRepository;
import com.crm.service.UserService;
import com.crm.util.MD5;

import freemarker.template.utility.StringUtil;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;

@Autowired
private ModuleRepository moduleRepository;

@Autowired
private UserCheckRepository ucRepository;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Override
	public User findByUname(String userName) {
		// TODO Auto-generated method stub
		return userRepository.findByUserName(userName);
	}

	@Override
	public Page<User> findByUser(User u, Pageable pageable,String bmName) {
		// TODO Auto-generated method stub
		return userRepository.findAll(get(u,bmName), pageable);
	}

	private Specification<User> get(User u,String bmName) {
		// TODO Auto-generated method stub
		return new Specification<User>() {

			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(u.getUserName())) {
					expressions.add(criteriaBuilder.like(root.get("userName"), "%"+u.getUserName()+"%"));
				}
				if(u.getUserIsLockout()!=null) {
					expressions.add(criteriaBuilder.equal(root.get("userIsLockout"), u.getUserIsLockout()));
				}
				if(!StringUtils.isEmpty(bmName)) {
					expressions.add(criteriaBuilder.like(root.get("bm").get("bmName"),"%"+bmName+"%"));
				}
				return predicate;
			}
		};
	}

	@Override
	public User AddAndUpdate(User u) {
		u.setUserIsLockout(0);
		u.setCheckState("未签到");
		return userRepository.saveAndFlush(u);
	}

	@Override
	public Integer DelUser(String userId) {
		// TODO Auto-generated method stub
		try {
			userRepository.deleteById(userId);
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			userRepository.deleteById(userId);
			return 0;
		}
		
	}

	@Override
	public String FinPwdAndNewPwd(String uname,String phone, String password) {
		// TODO Auto-generated method stub
		try {
		User u=	userRepository.finBynameandPhone(uname, phone);
		if(u!=null) {
			
			if(userRepository.updPwdByNewPwd(uname, MD5.JiaM(password))>0) {
				System.out.println("更改成功");
				return "成功";
			}else {
				System.out.println("在新密码发生了错误");
				return "失败";
			}
		}else {
			return "请输入正确信息";
		}
		} catch (Exception e) {
			// TODO: handle exception
			return "发生了错误请稍后再试";
		}
	}

	    @Transactional
	    @Override
	    public String Updatelockwrotime(String loginName) {
	        String updatelock = userRepository.Updatelock(loginName);
	        String updatewrotime = userRepository.Updatewrotime(loginName);
	        if(updatelock!=null||updatewrotime!=null){
	            try {
	                userRepository.updateTime(loginName);
	                return "操作成功";
	            }catch (Exception e){
	                e.printStackTrace();
	                return "操作失败";
	            }
	        }else{
	            return "操作失败";

	        }
	    }
	@Transactional
	@Override
	public void updateIsLockOut(String loginName) {
		// TODO Auto-generated method stub
		userRepository.updateIsLockOut(loginName);
	}

	@Override
	public List<Module> getUser_Role_ModuleByUserId(String id) {
		// TODO Auto-generated method stub
		return moduleRepository.getUser_Role_ModuleByUserId(id);
	}

	@Override
	public String jieFeng(String id) {
		try {
			userRepository.jieFeng(id,sdf.format(new Date()));
			return "解封成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "解封失败";
		}
		
	}

	@Override
	public String suoDing(String id) {
		try {
			userRepository.suoDing(id,sdf.format(new Date()));
			return "锁定成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "锁定失败";
		}
	}

	@Override
	public String user_roleManage(String id, String roleId) {
		//先删除所有用户角色关系
		userRepository.deleteUser_Role(id);
		userRepository.deleteUser_Asker(id);
		userRepository.deleteUser_NetAsker(id);
		//取出所有角色id
		String[] rids=roleId.split(",");
		//遍历添加用户角色关系
		for(int i=0;i<rids.length;i++) {
			userRepository.addUser_Role(id, Integer.valueOf(rids[i]));
			//判断此用户是否被设置为咨询师或网络咨询师
			if(Integer.valueOf(rids[i])==2) {
				
				userRepository.addUser_Asker(id);
				
			}
			if(Integer.valueOf(rids[i])==3) {
				userRepository.addUser_NetAsker(id);
				
			}
		}
		return "修改成功";
	}

	@Override
	public Integer updateCheckState(String id, String checkState,String userName,Integer type) {
		UserChecks uc=new UserChecks();
		if(type==0) {
			uc.setCheckInTime(sdf.format(new Date()));
			uc.setUserId(id);
			uc.setUserName(userName);
			uc.setCheckState(checkState);
			ucRepository.saveAndFlush(uc);
		}else {
			uc=ucRepository.getUserChecksById_CheckState(id);
			uc.setCheckOutTime(sdf.format(new Date()));
			uc.setCheckState(checkState);
			ucRepository.saveAndFlush(uc);
		}
		return userRepository.updateCheckState(id, checkState);
	}

	@Override
	public Integer reSetCheckState() {
		
		return userRepository.reSetCheckState();
	}

	@Override
	public Map<String, Object> userStaticCharts() {
		List<String> slist=new ArrayList<String>();
		slist.add("未签到的人数");
		slist.add("已签到的人数");
		List<Integer> pnum=new ArrayList<Integer>();
		pnum.add(userRepository.countCheckOut());//把未签到的人数存入
		pnum.add(userRepository.countCheckIn());//把签到的存入
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("checkState", slist);
		map.put("checkNum", pnum);
		Map<String, Object> circle=new HashMap<String, Object>();
		circle.put("checkOut",userRepository.countCheckOut());
		circle.put("checkIn", userRepository.countCheckIn());
		map.put("circle", circle);
		return map;
	}

	 
}
